﻿using System;
using System.Collections;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using AccountingLibs;

namespace Lists
{
    public class ListOfTableSynchronize
    {
        private static string _ConnectString = "";
        public ListOfTableSynchronize(string connectString)
        {
            _ConnectString = connectString;
            LoadFromDB();
            if (DataTable != null) _DataRow = DataTable.NewRow();
        }

        #region DataTable property
        private DataTable _DataTable;
        public DataTable DataTable
        {
            get
            {
                return _DataTable;
            }
        }
        #endregion

        #region DataRow property
        protected DataRow _DataRow = null;
        public DataRow DataRow
        {
            get
            {
                return _DataRow;
            }
            set
            {
                _DataRow = value;
            }
        }
        #endregion

        #region TableName property
        public string TableName
        {
            get
            {
                return (string)_DataRow["TableName"];
            }
            set
            {
                _DataRow["TableName"] = value;
            }
        }
        #endregion

        #region ActiveSynchronize property
        public bool ActiveSynchronize
        {
            get
            {
                return (bool)_DataRow["ActiveSynchronize"];
            }
            set
            {
                _DataRow["ActiveSynchronize"] = (bool)value;
            }
        }
        #endregion

        public void NewDoiTuong()
        {
            _DataRow = _DataTable.NewRow();
        }
        public virtual void InsertToDB()
        {
            SqlConnection con = new SqlConnection(_ConnectString);
            try
            {
                con.Open();
                SqlCommand cmd = con.CreateCommand();

                string values = ""; string listOfColumns = "";
                foreach (DataColumn column in this.DataRow.Table.Columns)
                {
                    values = values + "@" + column.ColumnName + ", ";
                    listOfColumns = listOfColumns + column.ColumnName + ", ";
                    cmd.Parameters.AddWithValue(column.ColumnName, DataRow[column.ColumnName]);
                }

                if (values.EndsWith(", ")) values = values.Substring(0, values.Length - 2);
                if (listOfColumns.EndsWith(", ")) listOfColumns = listOfColumns.Substring(0, listOfColumns.Length - 2);

                cmd.CommandText = string.Format("INSERT INTO {0}({1}) VALUES({2})",
                                                    this.DataRow.Table.TableName, listOfColumns, values);
                cmd.ExecuteNonQuery();
                if (this.DataRow.Table.Rows.IndexOf(this.DataRow) < 0) this.DataRow.Table.Rows.Add(this.DataRow);
            }
            catch (SqlException sqlEx)
            {
                throw new Exception(AccountingLibs.CommonLib.GetSqlExceptionMessage(sqlEx));
            }
            catch (Exception ex)
            {
            }
            finally
            {
                con.Close();
            }
        }
        public virtual void UpdateToDB()
        {
            SqlConnection con = new SqlConnection(_ConnectString);
            try
            {
                con.Open();
                SqlCommand cmd = con.CreateCommand();

                string values = "";
                foreach (DataColumn column in this.DataRow.Table.Columns)
                {
                    values += string.Format("{0} = @{0}, ", column.ColumnName);
                    cmd.Parameters.AddWithValue(column.ColumnName, DataRow[column.ColumnName]);
                }

                if (values.EndsWith(", ")) values = values.Substring(0, values.Length - 2);

                cmd.CommandText = string.Format("UPDATE {0} SET {1} WHERE TableName = '{2}'",
                                                    this.DataRow.Table.TableName,
                                                    values,
                                                    this.DataRow["TableName"]);
                cmd.ExecuteNonQuery();
            }
            catch (SqlException sqlEx)
            {
                throw new Exception(AccountingLibs.CommonLib.GetSqlExceptionMessage(sqlEx));
            }
            catch (Exception ex)
            {
                //Usual Code
            }
            finally
            {
                con.Close();
            }
        }
        public virtual void DeleteFromDB()
        {
            SqlConnection con = new SqlConnection(_ConnectString);
            try
            {
                con.Open();
                SqlCommand cmd = con.CreateCommand();
                cmd.CommandText = string.Format("DELETE FROM {0} WHERE TableName = '{1}'",
                                                    this.DataRow.Table.TableName,
                                                    this.DataRow["TableName"]);
                cmd.ExecuteNonQuery();
                _DataRow.Delete();
            }
            catch (SqlException sqlEx)
            {
                throw new Exception(AccountingLibs.CommonLib.GetSqlExceptionMessage(sqlEx));
            }
            catch (Exception ex)
            {
                //Usual Code
            }
            finally
            {
                con.Close();
            }
        }

        public void LoadFromDB()
        {
            using (SqlConnection con = new SqlConnection())
            {
                con.ConnectionString = _ConnectString;
                DataTable dt = new DataTable();
                SqlDataAdapter da = new SqlDataAdapter();
                try
                {
                    con.Open();
                    SqlCommand cmd = con.CreateCommand();
                    cmd.CommandText = "SELECT * FROM ListOfTableSynchronize";
                    da.SelectCommand = cmd;
                    da.Fill(dt);
                    _DataTable = dt;
                    _DataTable.TableName = "ListOfTableSynchronize";
                }
                catch (Exception ex)
                {
                    _DataTable = null;
                }
                finally
                {
                    if (con.State == ConnectionState.Open) con.Close();
                }
            }
        }

        public bool CheckByTableName(string tableName)
        {
            using (SqlConnection con = new SqlConnection())
            {
                con.ConnectionString = _ConnectString;
                SqlDataAdapter da = new SqlDataAdapter();
                try
                {
                    con.Open();
                    SqlCommand cmd = con.CreateCommand();
                    cmd.CommandText = string.Format("SELECT * FROM ListOfTableSynchronize WHERE TableName = {0}", tableName);
                    da.SelectCommand = cmd;
                    DataTable dt = new DataTable();
                    da.Fill(dt);
                    if (dt.Rows.Count > 0) return true;
                    else return false;
                }
                catch (Exception ex)
                {
                    return false;
                }
                finally
                {
                    if (con.State == ConnectionState.Open) con.Close();
                }
            }
        }

        public static ListOfTableSynchronize GetByTableName(string tableName)
        {
            using (SqlConnection con = new SqlConnection())
            {
                con.ConnectionString = _ConnectString;
                SqlDataAdapter da = new SqlDataAdapter();
                try
                {
                    con.Open();
                    SqlCommand cmd = con.CreateCommand();
                    cmd.CommandText = string.Format("SELECT * FROM ListOfTableSynchronize WHERE TableName = '{0}'", tableName);
                    da.SelectCommand = cmd;
                    DataTable dt = new DataTable();
                    da.Fill(dt);

                    ListOfTableSynchronize ListOfTableSynchronize = new ListOfTableSynchronize(_ConnectString);
                    if (dt.Rows.Count > 0)
                    {
                        ListOfTableSynchronize.TableName = (string)dt.Rows[0]["TableName"];
                        ListOfTableSynchronize.ActiveSynchronize = (bool)dt.Rows[0]["ActiveSynchronize"];
                        return ListOfTableSynchronize;
                    }
                    else
                    {
                        return null;
                    }
                }
                catch (Exception ex)
                {
                    return null;
                }
                finally
                {
                    if (con.State == ConnectionState.Open) con.Close();
                }
            }
        }

        public void AutoUpdateAllTableToListOfTableSynchronize()
        {
            SqlConnection con = new SqlConnection(_ConnectString);
            try
            {
                con.Open();
                SqlCommand cmd = con.CreateCommand();
                cmd.CommandText = "SELECT name TableName FROM SYS.TABLES";
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                da = new SqlDataAdapter(cmd);

                DataTable dt = new DataTable();
                da.Fill(dt);

                //Cập nhật những bảng chưa có vào CSDL
                foreach (DataRow row in dt.Rows)
                {
                    ListOfTableSynchronize record = GetByTableName(row["TableName"].ToString());
                    if (record == null)
                    {
                        ListOfTableSynchronize newRecord = new ListOfTableSynchronize(_ConnectString);
                        newRecord.TableName = row["TableName"].ToString();
                        newRecord.ActiveSynchronize = false;
                        newRecord.InsertToDB();
                    }
                }
            }
            catch (SqlException sqlEx)
            {
                throw new CustomException(CustomException.GetSqlExceptionMessage(sqlEx));
            }
            catch (Exception ex)
            {
                if (ex is CustomException) throw ex;
                else
                {
                    throw new CustomException(ex.Message);
                }
            }
            finally
            {
                LoadFromDB();
            }
        }
    }
}
